import {HTTP_INTERCEPTORS, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Injectable, Type} from '@angular/core';
import {Observable, of} from 'rxjs';
import {delay, dematerialize, materialize, mergeMap} from 'rxjs/operators';
import {MockData} from './MockData';
import {objectKeys} from "codelyzer/util/objectKeys";

@Injectable()
export class MockHttpInterceptor implements HttpInterceptor {

  static mockData: { [key: string]: MockData } = {};

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const key = objectKeys(MockHttpInterceptor.mockData).find(key => request.url.startsWith(key));

    if (!key) {
      return next.handle(request);
    } else {
      return of(null).pipe(mergeMap(() => {
        return of(MockHttpInterceptor.mockData[key].build(request));
      }))
        .pipe(materialize())
        .pipe(delay(500))
        .pipe(dematerialize());
    }
  }
}

export let mockHttpProvider = {
  provide: HTTP_INTERCEPTORS,
  useClass: MockHttpInterceptor,
  multi: true
};

export function GnMockData(path: string) {
  return (target: Type<any>) => {
    MockHttpInterceptor.mockData[path] = Reflect.construct(target, []);
  };
}
